package com.atguigu.controller;

import com.atguigu.entity.User;
import com.atguigu.service.UserService;
import com.atguigu.utils.JWTUtils;
import com.atguigu.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin // 允许跨域
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    /*
    * 用户登录
    * */
    @PostMapping("/login")
    public Result login(@RequestBody User user){

        Result result=new Result();
        try {
            //检查用户名密码
            User userDB = userService.checkLogin(user);
            // 生成 JWT - token
            Map<String, String> payload = new HashMap<>();
            payload.put("userId",userDB.getId().toString());
            payload.put("username",userDB.getUsername());
            String token = JWTUtils.getToken(payload);
            result.getMap().put("token",token);

            result.getMap().put("user",userDB);
            result.setStatus(true);
            result.setMessage("登录成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false);
            result.setMessage(e.getMessage());
        }finally {
            return result;
        }
    }
}
